import { http } from '../../request/index'
import {showModal, showToast} from '../../utilds/asyncWx'
Page({
  data: {
    address: {},
    cart:[],
    allChecked: false,
    totalPrice:0,
    totalNum:0
  },

  onLoad: function (options) {

  },
  onShow: function() {
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart') || [];
    //1种方法 const allChecked = cart.length ? cart.every(v => v.checked) : false;
    
    this.setData({address})
    this.setCart(cart)
  },
  //收货地址
  handleAddress() {
    wx.chooseAddress({
      success: (address) => {
        console.log(address)
        address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo
        wx.setStorageSync('address', address)
      },
    })
  },
  //商品的选中
  handeItemChange(e) {
    const {goods_id} = e.currentTarget.dataset;
    let {cart} = this.data;
    const index = cart.findIndex(v => v.goods_id === goods_id)
    cart[index].checked = !cart[index].checked
    
    this.setCart(cart)
  },

  //封装一个方法 改变勾选的同时计算 全选 总价 总数
  setCart(cart) {
    let allChecked = true;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if(v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num
      }else {
        allChecked = false
      }
    })
    allChecked = cart.length !=0 ? allChecked : false;
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNum
    })
    wx.setStorageSync('cart', cart)
  },

  //全选和反选
  handleAllCheck() {
    let {allChecked, cart} = this.data;
    allChecked = !allChecked;
    //让里面商品选中状态跟随allchecked 改变而改变
    cart.forEach(v => v.checked = allChecked);
    this.setCart(cart)
  },

  //数量改变
  async handleEditNum(e) {
    let {operation, goods_id} = e.currentTarget.dataset;
    let {cart} = this.data;
    const index = cart.findIndex(v => v.goods_id === goods_id);
    if(cart[index].num === 1 && operation === -1) {
      const res = await showModal({content:'您是否要删除？'})
      if(res.confirm) {
        cart.splice(index, 1)
        this.setCart(cart)
      }
    }else {
      cart[index].num += operation;
      this.setCart(cart)
    }
  },

  //结算
  async handlePay() {
    let {address, totalNum} = this.data;
    if(!address.userName) {
      await showToast({title: '请先选择收货地址'});
      return;
    }
    if(totalNum === 0) {
      await showToast({title: '请先选购商品'})
      return;
    }
    
    wx.navigateTo({
      url: '/pages/pay/index',
    })
  }
})